﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZEFTES
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        private double pbValue;
        public double PbValue
        {
            get { return pbValue; }
            set { pbValue = value; OnPropertyChanged("PbValue"); }
        }

        private void TestClick(object sender, RoutedEventArgs e)
        {
            string newPath = $"D:\\dats\\{DateTime.Now.ToString("yyyyMMddHHmmss")}_192_168_82_10.mdf";
            string sdb = "  D:\\VSProject\\MyCSharpProject\\ZEFTES\\Database1.mdf";
            System.IO.File.Copy(sdb, newPath);
            string connectStr = $"data source=(LocalDB)\\MSSQLLocalDB;attachdbfilename={newPath};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

            int maxValue = 3600 * 10;
            pbx.Maximum = maxValue;
            PbValue = 0;
            Database1Entities2 dbe = new Database1Entities2(connectStr);
            new Thread(new ThreadStart(() =>
            {
                for (int i = 1; i <= maxValue; i++)
                {
                    for (int j = 1; j <= 512; j++)
                    {
                        DateTime dt = DateTime.Now;
                        dbe.CnInfo.Add(new CnInfo
                        {
                            CnIdx = j,
                            RTime = dt,
                            ATime = i,
                            Volt = 3200
                        });
                    }
                    dbe.SaveChanges();
                    PbValue = i;
                }
            })).Start();
        }

        private void ProTest(object sender, RoutedEventArgs e)
        {
            string sdb = "D:\\VSProject\\MyCSharpProject\\ZEFTES\\Database1.mdf";
            string connectStr = $"data source=(LocalDB)\\MSSQLLocalDB;attachdbfilename={sdb};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

            //DateTime dt = DateTime.Now;
            //string sql = $"INSERT INTO {"CnInfo2"}(CnIdx,ATime,RTime,Volt) VALUES(@cnIdx, @at,@rt, @v)";
            //using (Database1Entities2 dbe = new Database1Entities2(connectStr))
            //{
            //    int x = 0;
            //    //var cItme = dbe.CnInfo2.Where(w => w.CnIdx == 144).FirstOrDefault();
            //    //var xxx = dbe.CnInfo2.ToList().Last().Num;
            //    //x = dbe.Database.ExecuteSqlCommand(sql, new SqlParameter[] {
            //    //                                //new SqlParameter("@tableName","CnInfo2"),
            //    //                                new SqlParameter("@cnIdx",144),
            //    //                                new SqlParameter("@at",DateTime.Now),
            //    //                                new SqlParameter("@rt",5),
            //    //                                new SqlParameter("@v",3120)
            //    //});
            //    x = dbe.InsertCnInfo("CnInfo2", 2, DateTime.Now, 789, 3120);
            //    //dbe.CnInfo2.Add(new CnInfo2 { CnIdx = 2, ATime = DateTime.Now, RTime = 1, Volt = 3122 });
            //    //x = dbe.SaveChanges();
            //    MessageBox.Show($"Successed:{x}");
            //}


            int maxValue = 3600 * 10;
            pbx.Maximum = maxValue;
            PbValue = 0;
            Database1Entities2 dbe = new Database1Entities2(connectStr);
            var cn1List = dbe.CnInfo2.Where(w => w.CnIdx == 1).ToList();
            //new Thread(new ThreadStart(() =>
            //{
            //    Random random = new Random(2950);
            //    for (int i = 1; i <= maxValue; i++)
            //    {
            //        for (int j = 1; j <= 512; j++)
            //        {
            //            dbe.InsertCnInfo("CnInfo2", j, DateTime.Now, i, random.Next(4200)); ;
            //        }
            //        PbValue = i;
            //    }
            //})).Start();
        }

        private void SqlBulkInsert(object sender, RoutedEventArgs e)
        {
            string sdb = "D:\\VSProject\\MyCSharpProject\\ZEFTES\\Database1.mdf";
            string connectStr = $"data source=(LocalDB)\\MSSQLLocalDB;attachdbfilename={sdb};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";
            Stopwatch sw = new Stopwatch();

            var con = new SqlConnection(connectStr);
            SqlBulkCopy bulk = new SqlBulkCopy(con);
            //表的名字
            bulk.DestinationTableName = "CnInfo6";
            DataTable dt = GetTableSchema();
            DateTime dt1 = DateTime.Now;
            int maxValue = 3600 * 20;
            pbx.Maximum = maxValue;
            PbValue = 0;
            Random random = new Random(2950);
            new Thread(new ThreadStart(() =>
            {
                try
                {
                    con.Open();
                    sw.Start();
                    for (int i = 1; i <= maxValue; i++)
                    {
                        for (int j = 1; j <= 512; j++)
                        {
                            var dr = dt.NewRow();
                            dr["CnIdx"] = j;
                            dr["ATime"] = DateTime.Now;
                            dr["RTime"] = i;
                            dr["Volt"] = random.Next(2500, 4200);
                            dt.Rows.Add(dr);
                        }
                        PbValue = i;
                        if (i % 2000 == 0)
                        {
                            bulk.BatchSize = dt.Rows.Count;
                            bulk.WriteToServer(dt);
                            dt.Rows.Clear();
                        }
                    }
                    if (dt.Rows.Count > 0)
                    {
                        bulk.BatchSize = dt.Rows.Count;
                        bulk.WriteToServer(dt);
                        dt.Rows.Clear();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    con.Close();
                    if (bulk != null)
                    {
                        bulk.Close();
                    }
                    sw.Stop();
                    MessageBox.Show($"Successed!{sw.ElapsedMilliseconds}");
                }
            })).Start();
        }
        private DataTable GetTableSchema()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] {
                new DataColumn("Num",typeof(int)),
                new DataColumn("CnIdx",typeof(int)),
                new DataColumn("ATime",typeof(DateTime)),
                new DataColumn("RTime",typeof(int)),
                new DataColumn("Volt",typeof(int))});
            return dt;
        }

        private void UseTVPsTest(object sender, RoutedEventArgs e)
        {
            //string sdb = "D:\\VSProject\\MyCSharpProject\\ZEFTES\\Database1.mdf";
            //string connectStr = $"data source=(LocalDB)\\MSSQLLocalDB;attachdbfilename={sdb};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

            //SqlConnection sqlconn = new SqlConnection(connectStr);
            //const string TSqlStatement =
            //      "insert into BulkTestTable (Id,UserName,Pwd)" +
            //      " SELECT nc.Id, nc.UserName,nc.Pwd" +
            //      " FROM @NewBulkTestTvp AS nc";
            //SqlCommand cmd = new SqlCommand(TSqlStatement, sqlconn);
            //SqlParameter catParam = cmd.Parameters.AddWithValue("@NewBulkTestTvp", dt);
            //catParam.SqlDbType = SqlDbType.Structured;
            //catParam.TypeName = "dbo.BulkUdt";
            //try
            //{
            //    sqlconn.Open();
            //    if (dt != null && dt.Rows.Count != 0)
            //    {
            //        cmd.ExecuteNonQuery();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("error>" + ex.Message);
            //}
            //finally
            //{
            //    sqlconn.Close();
            //}
        }
        private List<Thread> thList;
        private void CreateAndInsert(object sender, RoutedEventArgs e)
        {
            string sdb = "D:\\VSProject\\MyCSharpProject\\ZEFTES\\Database1.mdf";
            string connectStr = $"data source=(LocalDB)\\MSSQLLocalDB;attachdbfilename={sdb};integrated security=True;MultipleActiveResultSets=True;App=EntityFramework";

        }
    }
}
